#include "LCD12864.h"

// 延时函数
void delay_ms(unsigned int ms) {
    unsigned int i, j;
    for(i = 0; i < ms; i++)
        for(j = 0; j < 114; j++);
}

// 写命令到LCD
void LCD_WriteCmd(unsigned char cmd) {
    LCD_RS = 0;
    LCD_RW = 0;
    LCD_DATA = cmd;
    LCD_EN = 1;
    _nop_();
    LCD_EN = 0;
}

// 写数据到LCD
void LCD_WriteData(unsigned char dat) {
    LCD_RS = 1;
    LCD_RW = 0;
    LCD_DATA = dat;
    LCD_EN = 1;
    _nop_();
    LCD_EN = 0;
}

// 设置显示位置
void LCD_SetPos(unsigned char x, unsigned char y) {
    LCD_WriteCmd(0xb8 | y);
    LCD_WriteCmd(0x40 | x);
}

// LCD初始化
void LCD_Init() {
    LCD_RST = 0;
    delay_ms(1);
    LCD_RST = 1;
    
    LCD_CS1 = 1;
    LCD_CS2 = 1;
    
    LCD_WriteCmd(0x3f); // 开显示
    LCD_WriteCmd(0xc0); // 设置起始行
}

// 清屏
void LCD_Clear() {
    unsigned char i, j;
    for(j = 0; j < 8; j++) {
        LCD_SetPos(0, j);
        for(i = 0; i < 64; i++) {
            LCD_WriteData(0x00);
        }
    }
}

// 显示整张图片(128x64)
void LCD_ShowImage(unsigned char *img) {
    unsigned char x, y;
    for(y = 0; y < 8; y++) {
        LCD_SetPos(0, y);
        for(x = 0; x < 128; x++) {
            LCD_WriteData(img[y * 128 + x]);
        }
    }
}